<?php
require_once '../../controller.php';

$today_date = date('Y-m-d');
$today_date = strtotime($today_date);
$sql_query = mysql_query("SELECT * FROM `survey`") or die(mysql_error());
  while($s = mysql_fetch_object($sql_query)){
 	$surveys[] = $s;
 }
 
 foreach($surveys as $survey){
 	$survey_id = $survey->id;
 	$scheduled = $survey->schedule;
 	$last_sent = $survey->last_sent;
 	$scheduled_to_groups = $survey->scheduled_to_groups;
 	$email_subject = $survey->email_subject;
 	$email_message = $survey->email_message;
   
 	$scheduled_dates = explode(",",$scheduled);
 	$groups = explode(",",$scheduled_to_groups);
 	
 	if($last_sent!=''){
 	foreach($scheduled_dates as $s=>$value){
  			$last_sent = strtotime($last_sent);
 			$current = strtotime($value);
 			if($last_sent<$current ){
 				foreach($groups as $g=>$value){
 				 $group = new Group($value);
 				 $student_ids = $group->student_ids;
 				 foreach($student_ids as $key=>$id){
 				 	$s = new Student($id);
 				 	$survey_link = "http://".HOST."/survey/rendersurvey/publicsurvey.php?sid=".$survey_id."&mid=".$id;
 				 	$message= $email_message." ".$survey_link;
 				 	mail($s->email,$email_subject,$message,$headers);
 				 }
 				 	
 				}
 			$current_date = date('Y-m-d',$current);	
 			$sql = "UPDATE `survey` SET `last_sent`='$current_date' WHERE `id`='$survey_id'";
 			$result = mysql_query($sql)or die(mysql_error());	
 			break;
 			}
 		}
 		
 	}elseif($last_sent==''){
 		foreach($scheduled_dates as $s=>$value){
  			$current = strtotime($value);
 		 		
 		if($today_date > $current || $today_date == $current){
 		   foreach($groups as $g=>$value){
 				 $group = new Group($value);
 				 $student_ids = $group->student_ids;
 				 foreach($student_ids as $key=>$id){
 				 	$s = new Student($id);
 				 	$survey_link = "http://".HOST."/survey/rendersurvey/publicsurvey.php?sid=".$survey_id."&mid=".$id;
 				 	$message= $email_message." ".$survey_link;
 				 	mail($s->email,$subject,$message,$headers);
 				 }	
 				}
 			$current_date = date('Y-m-d',$current);	
 			$sql = "UPDATE `survey` SET `last_sent`='$current_date' WHERE `id`='$survey_id'";
 			$result = mysql_query($sql)or die(mysql_error());	
 			break;	
 		}
 	}	
 	}
 }



?>